# Agent数据流追踪 - 完整演示
# 这个文件展示了Agent间数据传递的详细过程

print("🔄 Agent协作数据流追踪演示")
print("=" * 50)

# 模拟用户请求
user_request = {
    "query": "我想去北京旅行3天，预算800欧元，喜欢历史景点和美食，对天气比较敏感",
    "timestamp": "2025-09-11T13:00:00"
}

print("1. 用户请求 → CoordinatorAgent")
print(f"   数据: {user_request}")
print()

# CoordinatorAgent意图分析
intent_analysis = {
    "primary_intent": "travel_planning",
    "city": "beijing",
    "duration": "3天",
    "budget": "800欧元",
    "needs_weather": True,
    "needs_attractions": True,
    "needs_restaurants": True,
    "special_requirements": "对天气比较敏感"
}

print("2. CoordinatorAgent意图分析")
print(f"   输入: {user_request['query']}")
print(f"   输出: {intent_analysis}")
print()

# 执行计划制定
execution_plan = {
    "steps": [
        {
            "agent": "weather",
            "input": {
                "type": "collaboration_request",
                "user_requirements": {"location": "beijing"},
                "collaboration_context": {"purpose": "travel_planning"}
            },
            "description": "获取天气信息和影响分析"
        },
        {
            "agent": "budget",
            "input": {
                "type": "collaboration_request",
                "user_requirements": {
                    "budget": "800欧元",
                    "location": "beijing",
                    "duration": "3天",
                    "preferences": "历史景点和美食，对天气比较敏感"
                },
                "upstream_context": {},
                "collaboration_context": {"purpose": "travel_planning"}
            },
            "description": "分析预算分配和成本优化"
        },
        {
            "agent": "travel",
            "input": {
                "city": "beijing",
                "weather_analysis": "来自weather_agent的结果",
                "budget_constraints": "来自budget_agent的结果"
            },
            "description": "获取景点推荐"
        },
        {
            "agent": "restaurant",
            "input": {
                "city": "beijing",
                "recommendations": "来自travel_agent的结果",
                "budget_constraints": "来自budget_agent的结果"
            },
            "description": "获取餐厅推荐"
        }
    ]
}

print("3. CoordinatorAgent制定执行计划")
print(f"   执行步骤数量: {len(execution_plan['steps'])}")
for i, step in enumerate(execution_plan['steps'], 1):
    print(f"   步骤{i}: {step['agent']}Agent - {step['description']}")
print()

# 模拟WeatherAgent协作请求
weather_input = {
    "type": "collaboration_request",
    "user_requirements": {"location": "beijing"},
    "collaboration_context": {"purpose": "travel_planning"}
}

weather_output = {
    "type": "collaboration_response",
    "agent": "IntelligentWeatherAgent",
    "weather_data": {
        "city": "Beijing",
        "current": "多云，温度27.65°C",
        "forecast_3day": [
            {"date": "2025-09-11", "condition": "partly_cloudy", "temp_high": 28, "temp_low": 18},
            {"date": "2025-09-12", "condition": "rainy", "temp_high": 22, "temp_low": 15},
            {"date": "2025-09-13", "condition": "sunny", "temp_high": 26, "temp_low": 17}
        ],
        "data_source": "mcp_tool_with_fallback"
    },
    "impact_analysis": {
        "outdoor_suitability": "中等",
        "indoor_recommendation": True,
        "cost_impact": "雨天可能增加交通成本"
    },
    "negotiation_points": [
        {
            "target_agent": "BudgetAgent",
            "topic": "weather_cost_impact",
            "proposal": "雨天需要额外交通预算",
            "justification": "第二天下雨可能需要打车或室内活动",
            "cost_impact": "+30-50€"
        }
    ],
    "potential_conflicts": [
        {
            "conflict_type": "weather_vs_budget",
            "severity": "medium",
            "description": "雨天可能增加出行成本"
        }
    ]
}

print("4. CoordinatorAgent → WeatherAgent")
print(f"   发送数据: {weather_input}")
print(f"   接收数据: {weather_output}")
print()

# 模拟BudgetAgent协作请求（包含天气影响）
budget_input = {
    "type": "collaboration_request",
    "user_requirements": {
        "budget": "800欧元",
        "location": "beijing",
        "duration": "3天",
        "preferences": "历史景点和美食，对天气比较敏感"
    },
    "upstream_context": {
        "weather_impact": {
            "extra_transportation_cost": 50,
            "equipment_cost": 0,
            "weather_condition": "多云转雨",
            "indoor_preference": True
        }
    },
    "collaboration_context": {"purpose": "travel_planning"}
}

budget_output = {
    "type": "collaboration_response",
    "agent": "BudgetAgent",
    "budget_data": {
        "base_budget": 800,
        "estimated_cost": 880,
        "budget_status": "tight",
        "optimized_breakdown": {
            "accommodation": 240,
            "food": 240,
            "transportation": 130,  # 增加了天气影响
            "activities": 160,
            "emergency": 30
        },
        "flexibility_analysis": {
            "can_reduce": 80,
            "savings_options": ["降级住宿", "减少活动预算", "优化餐饮"]
        }
    },
    "negotiation_points": [
        {
            "target_agent": "WeatherAgent",
            "topic": "budget_constraint_resolution",
            "proposal": "需要天气建议来优化预算分配",
            "justification": "预算紧张，需要天气指导来选择低成本活动",
            "required_savings": 80
        }
    ],
    "cost_optimization_suggestions": [
        "选择青年旅社替代酒店 (-60€)",
        "雨天选择免费室内景点 (-40€)",
        "超市自制餐饮替代餐厅 (-20€)"
    ]
}

print("5. CoordinatorAgent → BudgetAgent (包含天气影响)")
print(f"   发送数据: {budget_input}")
print(f"   接收数据: {budget_output}")
print()

# 模拟协商过程
negotiation_request = {
    "type": "negotiation_request",
    "sender": "BudgetAgent",
    "negotiation_id": "neg_12345",
    "negotiation_context": {
        "issue": "预算不足80€，需要成本优化方案",
        "proposal": "雨天需要额外交通费和室内活动预算",
        "details": {
            "current_shortfall": 80,
            "weather_impact": 50,
            "required_savings": 80
        }
    },
    "proposals": [
        {
            "type": "cost_reduction",
            "target": "activities",
            "request": "推荐免费/低成本的北京景点",
            "potential_savings": 40
        },
        {
            "type": "weather_adaptation",
            "request": "雨天的室内免费活动推荐",
            "potential_savings": 30
        }
    ],
    "user_requirements": intent_analysis
}

negotiation_response = {
    "type": "negotiation_response",
    "sender": "WeatherAgent",
    "negotiation_id": "neg_12345",
    "solutions": [
        {
            "category": "免费景点",
            "options": [
                "天坛公园 (免费)",
                "雍和宫 (免费)",
                "什刹海 (免费步行)"
            ],
            "savings": "45€",
            "weather_suitability": "雨天室内替代"
        },
        {
            "category": "低成本交通",
            "options": [
                "地铁日票替代出租车",
                "步行+公交组合"
            ],
            "savings": "35€",
            "weather_adaptation": "避开雨天高峰"
        }
    ],
    "total_savings": "80€",
    "negotiation_status": "agreement_reached",
    "confidence": 0.85
}

print("6. BudgetAgent → WeatherAgent 协商")
print(f"   协商请求: {negotiation_request}")
print(f"   协商响应: {negotiation_response}")
print()

# 模拟TravelAgent和RestaurantAgent的调用
travel_input = {
    "city": "beijing",
    "weather_analysis": weather_output,
    "budget_constraints": budget_output
}

travel_output = {
    "agent": "TravelAgent",
    "city": "beijing",
    "weather_considered": True,
    "recommendations": [
        {
            "name": "故宫博物院",
            "type": "历史景点",
            "reason": "室内历史展览，适合雨天",
            "note": "建议早晚时段避开高峰"
        },
        {
            "name": "天坛公园",
            "type": "皇家园林",
            "reason": "免费景点，雨天室内殿堂",
            "note": "祈年殿是北京标志性建筑"
        },
        {
            "name": "雍和宫",
            "type": "寺庙",
            "reason": "免费参观，室内古建筑",
            "note": "北京最大的藏传佛教寺庙"
        }
    ],
    "total_attractions": 3
}

print("7. CoordinatorAgent → TravelAgent")
print(f"   发送数据: 城市={travel_input['city']}, 天气已考虑, 预算已考虑")
print(f"   接收数据: 推荐{travel_output['total_attractions']}个景点")
print()

restaurant_input = {
    "city": "beijing",
    "recommendations": travel_output["recommendations"],
    "budget_constraints": budget_output,
    "weather_info": weather_output["weather_data"]
}

restaurant_output = {
    "agent": "RestaurantAgent",
    "city": "beijing",
    "based_on_attractions": ["故宫博物院", "天坛公园", "雍和宫"],
    "restaurant_recommendations": [
        {
            "name": "全聚德(前门店)",
            "type": "北京烤鸭",
            "price": "中档",
            "location_reason": "靠近故宫博物院"
        },
        {
            "name": "海碗居",
            "type": "老北京菜",
            "price": "平价",
            "location_reason": "靠近天坛公园"
        },
        {
            "name": "锦馨豆花庄",
            "type": "豆花饭庄",
            "price": "平价",
            "location_reason": "雍和宫附近特色小吃"
        }
    ],
    "total_restaurants": 3
}

print("8. CoordinatorAgent → RestaurantAgent")
print(f"   发送数据: 基于{len(restaurant_input['recommendations'])}个景点, 预算已考虑")
print(f"   接收数据: 推荐{restaurant_output['total_restaurants']}家餐厅")
print()

# 最终结果整合
final_result = {
    "user_query": user_request["query"],
    "intent_analysis": intent_analysis,
    "weather_info": weather_output["weather_data"],
    "budget_plan": budget_output["budget_data"],
    "attractions": travel_output["recommendations"],
    "restaurants": restaurant_output["restaurant_recommendations"],
    "negotiation_summary": {
        "total_negotiations": 1,
        "resolved_issues": 1,
        "total_savings": "80€",
        "success_rate": "100%"
    }
}

print("9. CoordinatorAgent整合最终结果")
print(f"   输入: 所有Agent结果 + 协商日志")
print(f"   输出: 完整的旅行规划方案")
print()

print("🔄 数据流追踪总结")
print("=" * 30)
print("数据传递序列:")
print("1. User → CoordinatorAgent (用户请求)")
print("2. CoordinatorAgent → WeatherAgent (天气查询)")
print("3. CoordinatorAgent → BudgetAgent (预算分析+天气影响)")
print("4. BudgetAgent → WeatherAgent (协商请求)")
print("5. WeatherAgent → BudgetAgent (协商响应)")
print("6. CoordinatorAgent → TravelAgent (景点推荐)")
print("7. CoordinatorAgent → RestaurantAgent (餐厅推荐)")
print("8. CoordinatorAgent → User (最终结果)")
print()
print("关键数据转换:")
print("• 用户自然语言 → 结构化意图分析")
print("• 天气原始数据 → 旅行影响分析 + 协商点")
print("• 预算约束 → 成本优化方案 + 协商需求")
print("• Agent协商 → 优化后的解决方案")
print("• 多Agent结果 → 整合的旅行规划")
print()
print("🎯 数据流特点:")
print("• 顺序传递: 每个Agent的结果都传递给下一个")
print("• 上下文增强: 后一个Agent接收前面的所有上下文")
print("• 协商循环: 发现冲突时触发Agent间协商")
print("• 结果整合: CoordinatorAgent整合所有结果")
print()
print("📊 数据流追踪价值:")
print("• 透明性: 清楚了解每个Agent的输入输出")
print("• 可调试性: 能够追踪问题出现在哪个环节")
print("• 可优化性: 发现性能瓶颈和改进点")
print("• 可学习性: 为后续优化提供数据基础")
